package com.example.blog_system.security;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.security.core.Authentication;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;
import java.util.Collections;
import java.util.Arrays;
import java.util.List;

public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenProvider tokenProvider;

    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    private final AntPathMatcher pathMatcher = new AntPathMatcher();

    // 定义公开路径列表
    private final List<String> publicPaths = Arrays.asList(
        "/",
        "/api/auth/**",
        "/login",
        "/register",
        "/css/**",
        "/js/**",
        "/error"
    );

    // 检查路径是否是公开路径
    private boolean isPublicPath(String path) {
        return publicPaths.stream()
            .anyMatch(pattern -> pathMatcher.match(pattern, path));
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        try {
            logger.debug("开始处理请求: " + request.getRequestURI());
            Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
            logger.debug("现有认证状态: " + (existingAuth != null ? existingAuth.getName() : "null"));

            // 如果已经有认证信息，不需要处理JWT
//            if (existingAuth != null &&
//                existingAuth.isAuthenticated() &&
//                !(existingAuth instanceof AnonymousAuthenticationToken)) {
//                logger.debug("已存在有效认证，跳过JWT处理");
//                filterChain.doFilter(request, response);
//                return;
//            }

            String jwt = getJwtFromRequest(request);
            logger.debug("从请求中获取的JWT: " + (jwt != null ? "存在" : "不存在"));

            if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
                Long userId = tokenProvider.getUserFromJWT(jwt).getId();
                logger.debug("JWT中的用户ID: " + userId);
                UserDetails userDetails = customUserDetailsService.loadUserById(userId);
                logger.debug("加载到的用户信息: " + userDetails.getUsername());
                
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                SecurityContextHolder.getContext().setAuthentication(authentication);
                logger.debug("已设置认证信息到SecurityContext");
                
                // 如果是API请求，不创建session
                if (!request.getRequestURI().startsWith("/api/")) {
                    request.getSession(true);
                    logger.debug("已创建session (非API请求)");
                }
            } else {
                logger.debug("JWT无效或不存在");
                // 检查是否是公开路径
                String requestPath = request.getRequestURI();
                if (!isPublicPath(requestPath)) {
                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().write("{\"code\":401,\"message\":\"未登录或登录已过期\"}");
                    return;
                }
            }
        } catch (Exception ex) {
            logger.error("无法设置用户认证", ex);
            SecurityContextHolder.clearContext();
        }

        filterChain.doFilter(request, response);
    }

    private String getJwtFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
} 